﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Daphne.Modularity.Storage
{
    /// <summary>
    /// Class for saving the client's storage
    /// </summary>
    public class ClientStorage : Dictionary<string, object>
    {
        /// <summary>
        /// Prefix for keys - used for child-controls of the page
        /// </summary>
        public string KeyPrefix
        { get; set; }

        public ClientStorage()
        {
            ClearKeyPrefix();
        }

        /// <summary>
        /// Clear the key-prefix
        /// </summary>
        public void ClearKeyPrefix()
        {
            KeyPrefix = string.Empty;
        }

        /// <summary>
        /// Returns value from the page state
        /// </summary>
        public T Get<T>(string key, T defaultValue = default(T))
        {
            // try to get value from the dictionary
            object objValue;
            if (base.TryGetValue(key, out objValue) == false)
                return defaultValue;

            // check the type
            if (!(objValue is T))
                return defaultValue;

            return (T)objValue;
        }

        /// <summary>
        /// Sets the value of page state
        /// </summary>
        public void Set<T>(string key, T value)
        {
            base[key] = value;
        }
    }


    /// <summary>
    /// Interface for classes supporting save / restore to the central storage
    /// </summary>
    public interface ISaveRestore
    {
        /// <summary>
        /// Key representing given instance
        /// </summary>
        string Key
        { get; }

        /// <summary>
        /// Loading method
        /// </summary>
        void LoadState(ClientStorage storage);

        /// <summary>
        /// Saving method
        /// </summary>
        void SaveState(ClientStorage storage);
    }
}
